package com.ghery.ftp.client;

import com.ghery.ftp.config.FtpConfiguration;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ghery
 * @date 2020/10/28 18:28
 * @desc FTP连接池
 */

public class FtpClientPool{

    private static final Logger log = LoggerFactory.getLogger(FtpClientFactory.class);

    private static volatile GenericObjectPool<FTPClient> ftpClientPool = null;

    /**
     * 获取FTP连接池
     * @param configuration
     * @return 连接池
     */
    public static GenericObjectPool<FTPClient> getFTPPool(FtpConfiguration configuration){
        if(ftpClientPool == null){
            synchronized (FtpClientPool.class){
                if(ftpClientPool == null){
                    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
                    config.setMaxIdle(configuration.getMaxIdle());
                    config.setMinIdle(configuration.getMinIdle());
                    config.setMaxTotal(configuration.getMaxTotal());
                    config.setTestOnBorrow(true);
                    config.setTestOnReturn(false);
                    config.setTestWhileIdle(true);
                    ftpClientPool = new GenericObjectPool<>(new FtpClientFactory(configuration),config);
                    if(log.isDebugEnabled()) {
                        log.debug("ftp pool init success,ip:{},port:{}", configuration.getIp(), configuration.getPort());
                    }
                }
            }
        }
        return ftpClientPool;
    }
}